import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/constants.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/controller/books.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/models/book/BookSearchDto.dart';
import 'package:ichinesereader/models/class/ClassDetailsNew.dart';
import 'package:ichinesereader/routes/routePages.dart';
import 'package:ichinesereader/themes/appTheme.dart';
import 'package:ichinesereader/themes/pageStyles.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/grids/bookGridWithCheckBoxTeaching.dart';
import 'package:ichinesereader/widgets/layouts/appdrawerTeacher.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';
import 'package:ichinesereader/widgets/buttons/floatingActionButtonAddBooksToFolder.dart';
import 'package:ichinesereader/widgets/sidebars/teacherSidebar.dart';

// ignore: must_be_immutable
class ProgramThemeBooksTeacherPage extends StatefulWidget {
  ProgramThemeBooksTeacherPage({
    Key? key,
    this.programId,
  }) : super(key: key);
  static const String routeName = '/teacher/themedbooks';
  String? programId;
  ProgramThemeBooksTeacherPageState createState() =>
      new ProgramThemeBooksTeacherPageState();
}

class ProgramThemeBooksTeacherPageState
    extends State<ProgramThemeBooksTeacherPage> {
  final box = Hive.box('appconfig');
  final BooksController _controller = Get.find();
  final SchoolAdminController _schoolAdminController = Get.find();
  String? _selectedSubProgramId;
  List<Tree> programTree = [];
  List<Tree> subProgramTree = [];
  List<Tree> subsubProgramTree = [];
  int limit = 20;
  int selectedPageNumber = 1;
  BookSearchDto dto = new BookSearchDto();

  void searchThemedBooks(String query) {
    dto.query = query;
    selectedPageNumber = 1;
    _controller.fetchProgramThemeBookItems(limit, selectedPageNumber - 1, dto);
  }

  void initState() {
    bool isTeacher = box.get(CacheManagerKey['nanhairole'].toString()) ==
        Constants.NanhaiRole_Teacher;
    widget.programId =
        box.get(CacheManagerKey['currentclassProgramId'].toString());

    // String _classDetails =
    //     box.get(CacheManagerKey['currentclassdetails'].toString());

    Future.delayed(Duration(milliseconds: 50), () {
      if (isTeacher) {
        try {
          // var cdn = ClassDetailsNew();
          // if (_classDetails != '') {
          //   cdn = classDetailsNewFromJson(_classDetails);
          // }
          if (widget.programId != null && widget.programId != '') {
            dto.programKind = [];
            // if (cdn.program != null && cdn.program?.tree != null) {
            //   programTree = cdn.program?.tree!.lowerProgram as List<Tree>;
            //   var tempTree = programTree.firstWhere(
            //       (element) => element.id == programId,
            //       orElse: null);
            //   if (tempTree.lowerProgram != null) {
            //     subProgramTree = tempTree.lowerProgram as List<Tree>;
            //   }
            //   dto.programKind?.add(subProgramTree[0].id.toString());
            // } else {
            //   dto.programKind?.add(programId.toString());
            // }

            if (_schoolAdminController.currentClassPrograms.value.tree !=
                null) {
              programTree = _schoolAdminController
                  .currentClassPrograms.value.tree!.lowerProgram as List<Tree>;
              var tempTree = programTree.firstWhere(
                  (element) => element.id == widget.programId,
                  orElse: null);
              if (tempTree.lowerProgram != null) {
                subProgramTree = tempTree.lowerProgram as List<Tree>;
              }
              dto.programKind?.add(subProgramTree[0].id.toString());
            } else {
              dto.programKind?.add(widget.programId.toString());
            }
            _controller.fetchProgramThemeBookItems(
                limit, selectedPageNumber - 1, dto);
          } else {}
        } catch (error) {
          Log.debug(error);
        }
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    _controller.selectedThemedBookItems.clear();
    _controller.themedBookItems.clear();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build ProgramThemeBooksTeacherPage');

    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;
    final isBigScreen =
        MediaQuery.of(context).size.width > Constants.DefinedScreenBigSize;
    int _selectedSidebarItem = RoutePages.teacherPageItems.indexWhere((page) =>
        page.route == '/teacher/themedbooks' ||
        page.route == '/teacher/corematerials');
    final PageStyles _pageStyles = PageStyles();

    return Scaffold(
        appBar: isSmallScreen ? CustomAppBar(title: 'Core Materials'.tr) : null,
        drawer: isSmallScreen ? TeacherAppDrawer() : null,
        body: Container(
          decoration: _pageStyles.pageBoxDecoration(),
          child: Row(
            children: [
              Visibility(
                  visible: !isSmallScreen,
                  child: TeacherSidebarX(
                    selectedIndex: _selectedSidebarItem,
                    isBigScreen: isBigScreen,
                  )),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(0.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          Obx(() {
                            if (_schoolAdminController
                                        .currentClassPrograms.value.id !=
                                    null &&
                                _schoolAdminController
                                        .currentClassPrograms.value.tree !=
                                    null) {
                              programTree = _schoolAdminController
                                  .currentClassPrograms
                                  .value
                                  .tree!
                                  .lowerProgram as List<Tree>;

                              var tempTree = programTree.firstWhere(
                                  (element) => element.id == widget.programId,
                                  orElse: null);

                              if (tempTree.lowerProgram != null) {
                                subProgramTree =
                                    tempTree.lowerProgram as List<Tree>;

                                return Container(
                                  margin: const EdgeInsets.only(top: 18),
                                  width: 280,
                                  height: 58,
                                  child: DropdownButtonFormField(
                                      dropdownColor: Get.isDarkMode
                                          ? AppTheme.colors.darkTheme2
                                          : Get.theme.primaryColorDark,
                                      isExpanded: true,
                                      value: subProgramTree[0],
                                      decoration: InputDecoration(
                                        contentPadding:
                                            EdgeInsets.only(left: 15.0, top: 6),
                                        labelStyle: TextStyle(
                                            color: Get.isDarkMode
                                                ? Get.theme.primaryColorDark
                                                : Colors.black),
                                        labelText: 'Themes'.tr,
                                      ),
                                      items: subProgramTree
                                          .map((program) => DropdownMenuItem(
                                                value: program,
                                                child: Text(
                                                  program.name.toString(),
                                                  style: TextStyle(
                                                      fontSize: 14.0,
                                                      color: Get.isDarkMode
                                                          ? Get.theme
                                                              .primaryColorDark
                                                          : Get.theme
                                                              .primaryColorLight),
                                                  overflow: TextOverflow.fade,
                                                  softWrap: true,
                                                ),
                                              ))
                                          .toList(),
                                      onChanged: (value) {
                                        var item = value as Tree;

                                        if (item.id != null) {
                                          _selectedSubProgramId =
                                              item.id.toString();
                                          _schoolAdminController
                                              .setSubThemeProgramId(
                                                  _selectedSubProgramId
                                                      .toString());

                                          dto = new BookSearchDto();
                                          dto.programKind = [];
                                          dto.programKind
                                              ?.add(item.id.toString());
                                          _controller
                                              .selectedThemedBookItemsClear();
                                          _controller.themedBookItems.clear();
                                          selectedPageNumber = 1;
                                          _controller
                                              .fetchProgramThemeBookItems(limit,
                                                  selectedPageNumber - 1, dto);
                                        }
                                      }),
                                );
                              } else {
                                return Text('');
                              }
                            } else {
                              return Text('');
                            }
                          }),
                          Obx(() {
                            if (_schoolAdminController
                                    .selectedSubThemeProgramId.value !=
                                '') {
                              programTree = _schoolAdminController
                                  .currentClassPrograms
                                  .value
                                  .tree!
                                  .lowerProgram as List<Tree>;
                              subProgramTree = programTree
                                  .firstWhere((element) =>
                                      element.id == widget.programId)
                                  .lowerProgram as List<Tree>;
                              var tempTree = subProgramTree.firstWhere(
                                  (element) =>
                                      element.id ==
                                      _schoolAdminController
                                          .selectedSubThemeProgramId.value);
                              if (tempTree.lowerProgram != null) {
                                subsubProgramTree =
                                    tempTree.lowerProgram as List<Tree>;

                                if (subsubProgramTree.isNotEmpty) {
                                  return Expanded(
                                    child: Padding(
                                      padding: const EdgeInsets.fromLTRB(
                                          12, 0, 0, 8),
                                      child: Column(
                                        children: <Widget>[
                                          FormBuilderChoiceChip(
                                            shadowColor: Get.isDarkMode
                                                ? Colors.black
                                                : Colors.black.withOpacity(0.6),
                                            backgroundColor: Get.isDarkMode
                                                ? Get.theme.primaryColor
                                                : AppTheme.colors.darkTheme9,
                                            selectedColor: Get.isDarkMode
                                                ? Get.theme.primaryColorDark
                                                : Theme.of(context)
                                                    .primaryColorDark,
                                            decoration: InputDecoration(
                                                labelText: '',
                                                border: InputBorder.none),
                                            name: 'subprogram_choice_chip',
                                            onChanged: (value) {
                                              if (value == null) return;

                                              var subprogram = value as Tree;
                                              // BookSearchDto dto =
                                              //     new BookSearchDto();
                                              dto = new BookSearchDto();
                                              dto.programKind = [];
                                              dto.programKind?.add(
                                                  subprogram.id.toString());
                                              // _controller.selectedThemedBookItems
                                              //     .clear();
                                              // _controller.themedBookItems.clear();
                                              _controller
                                                  .selectedThemedBookItemsClear();
                                              _controller.themedBookItems
                                                  .clear();
                                              selectedPageNumber = 1;
                                              _controller
                                                  .fetchProgramThemeBookItems(
                                                      limit,
                                                      selectedPageNumber - 1,
                                                      dto);
                                            },
                                            options: subsubProgramTree
                                                .map((program) =>
                                                    FormBuilderChipOption<Tree>(
                                                      value: program,
                                                      child: Text(
                                                        program.name.toString(),
                                                        style: TextStyle(
                                                          color: Get.isDarkMode
                                                              ? Colors.black
                                                              : Get.theme
                                                                  .primaryColorLight,
                                                          fontSize: 12,
                                                          letterSpacing: 1,
                                                        ),
                                                        overflow: TextOverflow
                                                            .ellipsis,
                                                      ),
                                                    ))
                                                .toList(),
                                          ),
                                        ],
                                      ),
                                    ),
                                  );
                                } else {
                                  return Text('');
                                }
                              } else {
                                return Text('');
                              }
                            } else {
                              return Text('');
                            }
                          }),
                        ],
                      ),
                      Flexible(
                          child: _controller.obx(
                        (data) => BookGridWithCheckBoxTeaching(
                          books: _controller.themedBookItems,
                          readingType: NanhaiBookReadingTypes.theme,
                        ),
                        onLoading: Container(),
                        onError: ((error) => Center(
                            child: Text('Oops, something wrong ...'.tr))),
                        onEmpty: Center(child: Text('Coming soon ...'.tr)),
                      )),
                      // Container(
                      //   child: Center(
                      //     child: _controller.obx(
                      //       (data) => NumberPagination(
                      //         key: themedPaginationKey,
                      //         onPageChanged: (int pageNumber) {
                      //           setState(() {
                      //             selectedPageNumber = pageNumber;
                      //             _controller.fetchProgramThemeBookItems(
                      //                 limit, selectedPageNumber - 1, dto);
                      //           });
                      //         },
                      //         pageTotal: _controller.themedBooksTotalNum.value %
                      //                     limit ==
                      //                 0
                      //             ? (_controller.themedBooksTotalNum.value ~/
                      //                     limit)
                      //                 .toInt()
                      //             : (_controller.themedBooksTotalNum.value ~/
                      //                         limit)
                      //                     .toInt() +
                      //                 1,
                      //         threshold: 5,
                      //         pageInit:
                      //             selectedPageNumber, // picked number when init page
                      //         colorPrimary: Theme.of(context).primaryColorLight,
                      //         colorSub: Theme.of(context).primaryColorDark,
                      //       ),
                      //     ),
                      //   ),
                      // ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        floatingActionButton: FloatingActionButtonAddBookToFolder(
          readingType: NanhaiBookReadingTypes.theme,
        ));
    //floatingActionButton: FloatingActionButtonThemedBooks());
  }
}
